<template>
    <div id="student-files-list">
        <div class="jx-content">
            <div class="search-box">
                <el-form :inline="true" ref="searchForm" v-model="searchForm">
                    <el-form-item class="casitem" label="班级 :">
                        <el-cascader
                            class="cascader"
                            :options="data"
                            expand-trigger="hover"
                            :props="cascaderconfig"
                            v-model="selectedOptions"
                            @change="getClass"
                            ></el-cascader>
                    </el-form-item>
                    <!-- <el-form-item>
                        <div class="button-style" @click="getList">搜 索</div>
                    </el-form-item> -->
                    <el-form-item>
                        <span class="subtitle">{{ dataTime }}</span>
                        <span v-if="!isUpDate" class="sdgx" @click="handRefresh">
                            <i class="iconfont icon-refresh"></i>
                            手动更新
                        </span>
                        <span v-else class="sdgx">
                            <i class="el-icon-loading"></i>
                            正在更新
                        </span>
                    </el-form-item>
                    <el-form-item class="fr">
                        <div class="download-style" @click="downloadPost">整体档案下载</div>
                    </el-form-item>
                </el-form>
            </div>
            <div class="table">
                <el-table  :data="tableData.data" ref="multipleTable"  style="width: 100%">
                    <el-table-column label="序号" width="60">
                        <template slot-scope="scope"><span>{{scope.$index+(tableData.pageNum - 1) * tableData.pageSize + 1}}</span> </template>
                    </el-table-column>
                    <el-table-column prop="studentClassName" label="班级"></el-table-column>
                    <el-table-column prop="grade" label="年级"></el-table-column>
                    <el-table-column prop="userNumber" label="学号"></el-table-column>
                    <el-table-column prop="name" label="姓名"></el-table-column>
                    <el-table-column fixed="right" label="操作" width="150">
                        <template slot-scope="scope">
                            <el-button @click="toDetails(scope.row)" type="text" size="small">查看</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="tableData.pageNum"
                    :page-size="tableData.pageSize"
                    layout="total, prev, pager, next, jumper"
                    :total="tableData.total">
                </el-pagination>
            </div>
        </div>
        <!-- <el-dialog :close-on-click-modal="false"  title="修改" :visible.sync="dialogable" width="550px" >
            <el-form class="demo-form-inline clearfix" :inline="true" :model="formInline"  label-width="90px">
                <el-form-item label="班级名称：" >
                    <el-input v-model="formInline.user" placeholder="请输入班级名称" maxlength="20"></el-input>
                </el-form-item>
                <el-form-item label="年级：">
                    <el-input-number v-model="formInline.class" controls-position="right" @change="handleChange" :min="2015"></el-input-number>
                </el-form-item>
            </el-form>
            <div class="button-style" style="width:90px; margin:0 auto; display:block" @click="onSubmit">保 存</div>
        </el-dialog>
        <el-dialog :close-on-click-modal="false" class="dialog-add-class" title="添加班级" :visible.sync="dialogAddClass" width="460px">
            <span slot="footer" class="dialog-footer" style="text-align:center; display: block;">
                <el-button class="button-style" style="width: 120px;" @click="jumpClass(1)">创建本课班级</el-button>
                <el-button class="button-style" style="width: 120px;" @click="jumpClass(2)">关联系统班级</el-button>
            </span>
        </el-dialog> -->
    </div>
</template>

<script>
    export default {
        data () {
            return {
                searchForm:{
                    chapterId:''
                },
                chapterList:[],
                tableData:{
                    data:[],
                    pageNum:1,
                    pageSize:10,
                    total:0,
                },
                classId:'',
                _cascaderconfig: {
                  value: "name",
                  label: "name",
                },
                get cascaderconfig() {
                  return this._cascaderconfig;
                },
                set cascaderconfig(value) {
                  this._cascaderconfig=value;
                },
                selectedOptions:[],
                idlist:[],
                data:[],
                userInfo:'',
                dataTime:'',
                websock:null,
                //正在更新
                isUpDate:false,
                courseId:'',

            }
        },
        created(){
            this.courseId = this.$localstorage.getLocalStorage('setCourseId')
            //this.getList()

        },
        destroyed() {
            this.websock.close() //离开路由之后断开websocket连接
        },
        mounted(){
            this.init();
            this.$nextTick(function(){
                this.initWebSocket();
            });
        },
        methods: {
            init(){
                this.getClass();
            },
//socket
            initWebSocket(){ //初始化websocket
                let hostname = window.location.host;
                const wsuri = "ws://" + hostname + "/tes/ws/global";
                this.websock = new WebSocket(wsuri);
                this.websock.onmessage = this.websocketonmessage;
                this.websock.onopen = this.websocketonopen;
                this.websock.onerror = this.websocketonerror;
                this.websock.onclose = this.websocketclose;
            },
            websocketonopen(){ //连接建立之后执行send方法发送数据
                console.log('链接成功');
                this.isUpDate = true;
                //let actions = {"teaching-statistics":"12345"};
                //this.websocketsend(JSON.stringify(actions));
            },
            websocketonerror(){//连接建立失败重连
                this.initWebSocket();
            },
            websocketonmessage(e){ //数据接收
                const redata = JSON.parse(e.data);
                console.log(redata,3212);
                let classId = this.classId;
                console.log(classId,redata.classId);
                if(redata.type == 50 && classId == redata.classId){
                    //this.isUpDate = false;
                    this.$message.success('更新成功');
                    this.getAllData(classId);
                }
            },
            websocketsend(Data){//数据发送
                this.websock.send(Data);
            },
            websocketclose(e){  //关闭
                console.log('断开连接',e);
            },
//socket end
            //获取班级
            getClass(){
                let self = this;
                ///course/课程id/search/list-class?allFlag=false
                self.$http.get('/tes/course/'+self.courseId+'/search/list-class?allFlag=false&defaultClassFlag=true').then((response) => {
                    let res = response.data
                    if(res.code == '200') {
                        console.log(res,26);
                        self.data = res.data
                        self.filterInitData(res.data)
                        self.ChangeList()
                    }else{
                        self.$message.error(res.message)
                    }
                })
            },
            //过滤数据获得默认值
            filterInitData(data){
                let self = this;
                data.forEach(function(item) {
                if (item.defaultedClass == true) {
                    self.selectedOptions.push(item.name)
                }
                if (item.children) {
                    item.children.forEach(function(it) {
                    if (it.defaultedClass == true) {
                        self.selectedOptions.push(it.name)
                    }
                    if (it.children) {
                        it.children.forEach(function(itChild) {
                        if (itChild.defaultedClass == true) {
                            self.selectedOptions.push(itChild.name)
                            }
                        })
                    }
                    })
                }
                });
                console.log(self.selectedOptions, 99)
                return self.selectedOptions
            },
            //获取id集合
            ChangeList(){
                let self = this
                if(self.selectedOptions[0]===undefined ||  self.selectedOptions[0]=='全部'){
                    self.selectedOptions[0]=''
                    self.selectedOptions[1]=''
                    self.selectedOptions[2]=''
                }else if(self.selectedOptions[1]===undefined || self.selectedOptions[1]=='全部'){
                    self.selectedOptions[1]=''
                    self.selectedOptions[2]=''
                }else if(self.selectedOptions[2]===undefined || self.selectedOptions[2]=='全部'){
                    self.selectedOptions[2]=''
                }
                self.$http.post('/tes/course/'+self.courseId+'/search/class',{
                    status :self.selectedOptions[0],
                    grade :self.selectedOptions[1],
                    name: self.selectedOptions[2]
                }) .then((response) => {
                    let res = response.data
                    if(res.code == '200') {
                        console.log(res,225567);
                        self.idlist=res.data
                        self.classId = res.data[0];
                        self.getAllData();
                    }else if(res.code == '404'){
                        self.$message(res.message)
                    }else{
                        self.$message.error(res.message)
                    }
                }).catch(err => {
                        console.log(err)
                })
            },
            
            selectChange(){},
            //获取列表数据
            getList() {
                let self = this;
                let classId = self.classId;
                let pageNum = self.tableData.pageNum;
                let pageSize = self.tableData.pageSize;
                let courseId = self.courseId;
                self.$http.post(`/tes/statistic/student/class/${classId}/page?courseId=${courseId}&pageNum=${pageNum}&pageSize=${pageSize}`,{
                    userInfo:self.userInfo,
                }).then((response) => {
                    let res = response.data;
                        if (res.code == "200") {
                            console.log(res,22423);
                            self.tableData.data = res.data.content;
                            self.tableData.total = res.data.total;
                        } else{
                            self.$message.error(res.message)
                        }
                    }).catch((err) => {
                        self.$message.error(res.message);
                    });
            },
            //分页
			handleSizeChange: function (size) {
				this.tableData.pageSize = size;
			},
			handleCurrentChange: function(currentPage) {
                this.tableData.pageNum = currentPage
                this.getList()
            },
            //获取数据统计截止时间
            getDataTime(){
                let self = this;
                let classId = self.classId;
                self.$http.get(`/tes/statistic/class/${classId}/update-time`).then((response) => {
                    let res = response.data
                    //时间
                    if(res.code == '200') {
                        console.log(res,223);
                        self.dataTime = `数据统计截止至 ${res.data}`;
                        self.isUpDate = false;
                    }
                    //暂未更新
                    if(res.code == '404'){
                        self.dataTime = '';
                        self.isUpDate = false;
                    }
                    //统正在对班级更新
                    if(res.code == '600100'){
                        self.dataTime = res.message;
                        self.isUpDate = true;
                    }
                }).catch(err => {
                    console.log(err);
                });
            },
            //获取所有数据
            getAllData(){
                this.getDataTime();
                this.getList();
            },
            //手动更新
            handRefresh(){
                let self = this;
                let classId = self.classId;
                self.$http.post(`/tes/statistic/class/${classId}`).then((response) => {
                    let res = response.data;
                    if(res.code == '200'){
                        //self.$message.success(res.message)
                        self.getDataTime();
                    }
                    else{
                        self.$message.error(res.message)
                    }
                }).catch(err => {
                    console.log(err);
                });
            },
            //查看
            toDetails(row){
                let self = this;
                self.$router.push({
                    path:'StudentFiles',
                    query: {
                        classId: self.classId,
                        userId:row.id,
                        courseId:self.courseId,
                    }
                });
            },
            //下载
            downloadPost(){
                let self = this
                let classId = self.classId;
                let className = self.selectedOptions[2];
                let courseId = self.courseId;
                self.downloadStatus = true
                self.downloadText = '下载中'
                self.$http.post(`/tes/statistic/student/class/${classId}/download?courseId=${courseId}`,{},{responseType: 'blob'}) .then((response) => {
                    let contentType = response.headers["content-type"]
                    console.log(response,22);
                    if (contentType == "application/json;charset=UTF-8") {
                        let codeMessage = response.headers["code-message"];
                        console.log(codeMessage);
                        let str = '';
                        if(codeMessage == 404){
                            str = '暂无统计';
                        }
                        if(codeMessage == 500){
                            str = '服务器内部错误';
                        }
                        if(codeMessage == 600100){
                            str = '当前班级正在统计中，请稍后再试';
                        }
                        self.$message.error(str);
                    }
                    else{
                        let contentType = response.headers["content-type"]
                        let blob = new Blob([response.data], {type: response.headers['content-disposition']});
                        let url = window.URL.createObjectURL(blob);
                        //let fileName = response.headers['content-disposition'].split(";")[1].split("filename=")[1];
                        let fileName = `${className}班级的学生统计.xls`;
                        let downloadElement = document.createElement('a');
                        downloadElement.style.display = 'none';
                        downloadElement.href = url;
                        downloadElement.download = fileName; //下载后文件名
                        document.body.appendChild(downloadElement);
                        downloadElement.click(); //点击下载 
                        document.body.removeChild(downloadElement); //下载完成移除元素
                        window.URL.revokeObjectURL(url);
                        self.downloadStatus = false
                        self.downloadText = ''
                    }
                }).catch(err => {
                    console.log(err)
                })
            }
        }
    }
</script>
<style lang="scss">
    #student-files-list{
        background: #f8f8f8;
        min-height: 500px;
        width: 1200px;
        margin: 0px auto 100px;
        color: #727272;
        .jx-content{
            margin: 0px;
            box-shadow: 0 0 10px rgba(0,0,0,0.05);    
            border-radius:0;
            padding-bottom:0px;
            .sfl-input{
                .el-input__inner{
                    width:200px;
                }
            }
        }
        .subtitle{
            font-size: 14px;
            color:#989898;
        }
        .sdgx{
            color:#385899;
            font-size: 16px;
            cursor: pointer;
            margin-left:20px;
        }
        .el-form-item{
            vertical-align:middle;
            .el-form-item__content{
                vertical-align: baseline;
            }
        }
        .el-button--text{
            &:hover{
                color:#1277eb;
            }
        }
    }
</style>
